package com.itheima.reggie.controller;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private HttpSession session;
    //http://localhost:8080/employee/1523136930055852000
    @GetMapping("/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        Employee employee=employeeService.findById(id);
        return ResultInfo.success(employee);
    }
    //http://localhost:8080/employee
    @PostMapping("")
    public ResultInfo save(@RequestBody Employee employee){
        employeeService.save(employee);
        return ResultInfo.success(null);
    }
    @PutMapping("")
    public ResultInfo update(@RequestBody Employee employee){
        employeeService.update(employee);
        return ResultInfo.success(null);
    }
    //http://localhost:8080/employee/find
    @GetMapping("/find")
    public ResultInfo find(String name){
    List<Employee> employees= employeeService.find(name);
    return ResultInfo.success(employees);
    }
    //http://localhost:8080/employee/logout
    @PostMapping("/logout")
    public ResultInfo logout(){
        session.invalidate();
      return ResultInfo.success(null);
    }

    @PostMapping("/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        String username = map.get("username");
        String password = map.get("password");
        ResultInfo resultInfo=employeeService.login(username,password);

        if (resultInfo.getCode()==1){
            Employee employee = (Employee)resultInfo.getData();
            session.setAttribute(Constant.SESSION_EMPLOYEE,employee);
        }
        return resultInfo;
    }
}
